from django.core.files import File
from api.user_management.serializers import UserSerializer
from django.views.decorators.csrf import csrf_exempt
import django.contrib.auth as auth
from rest_framework import status, viewsets
from rest_framework.decorators import api_view
from rest_framework.response import Response
# from .serializers import FileSerializer


@csrf_exempt
@api_view(['POST'])
def login(request):
    """
    验证用户并登录
    """
    # print('username', request.data['username'])
    # print('password', request.data['password'])
    user = auth.authenticate(username=request.data['username'],
                             password=request.data['password'])
    if user is not None:
        auth.login(request, user)
        serializer = UserSerializer(user, context={'request': request})
        return Response(serializer.data, status=status.HTTP_200_OK)
    else:
        return Response(status=status.HTTP_403_FORBIDDEN)


@api_view(['GET'])
def is_authenticated(request):
    """
    认证用户
    """
    # print('username', request.data['username'])
    # print('password', request.data['password'])
    user = request.user
    if user.is_authenticated:
        serializer = UserSerializer(user, context={'request': request})
        response = Response(serializer.data, status=status.HTTP_200_OK)
        # response.data['result'] = True
        return response
    else:
        # return Response({'result': False}, status=status.HTTP_200_OK)
        return Response({}, status=status.HTTP_200_OK)


@api_view(['GET'])
def logout(request):
    """
    注销用户
    """
    auth.logout(request)
    return Response(status=status.HTTP_200_OK)


# class FileUploadManagement(viewsets.ModelViewSet):
#     queryset = File.objects.all()
#     serializer_class = FileSerializer

@api_view(['GET'])
def has_permission(request):
    """
    检查权限
    """
    user = request.user
    permission = request.GET.get('permission')
    # print('permission:', permission)
    return Response({'result': user.has_perm(permission)}, status=status.HTTP_200_OK)
